import React, { Component } from 'react'
import styles from './Login.module.css'
import { withRouter } from 'react-router-dom'

class Login extends Component {
  constructor () {
    super()

    this.state = {
      username: '',
      password: ''
    }
  }

  change = e => {
    this.setState({
      // 属性名表达式
      [e.target.name]: e.target.value
    })
  }

  login = () => {
    const { username, password } = this.state

    if (username === 'admin' && password === '123') {
      localStorage.setItem('token', 'asdfasfasdf')

      // query传参
      if (this.props.location.search) {
        const searchParams = new URLSearchParams(this.props.location.search)
        const redirect = searchParams.get('redirect')

        this.props.history.push(redirect)
      } else {
        this.props.history.push('/layout')
      }

      // state传参
      // if (this.props.location.state) {
      //   this.props.history.push(this.props.location.state.redirect)
      // } else {
      //   this.props.history.push('/layout')
      // }

      // this.props.history.push('/layout')
      // 跳转
    } else {
      alert('用户名或是密码错误')
    }
  }

  render () {
    return (
      <div className={styles['login-container']}>
        xxx 管理系统登录
        <p>
          用户名：
          <input
            value={this.state.username}
            name='username'
            onChange={this.change}
          />
        </p>
        <p>
          密码：
          <input
            value={this.state.password}
            name='password'
            onChange={this.change}
          />
        </p>
        <p>
          <button onClick={this.login}>登录</button>
        </p>
      </div>
    )
  }
}

export default withRouter(Login)
